import React from 'react'
import { connect } from 'react-redux'
import { warn, success, Button, TitleBar, Checkbox } from '../../ui-components'
import style from './style.remind'
import util from '../../util'

export default
@connect(({ user }) => ({ user }))
class extends React.Component {

	changed = []

	state = {
		list: []
	}

	componentDidMount() {
		this.props.fetchRemindSettings()
	}

	componentWillUnmount() {
		this.props.resetUser()
	}

	componentWillReceiveProps(props) {
		if (!this.props.user.remindSettings.length && props.user.remindSettings.length) {
			this.setState({
				list: props.user.remindSettings
			})
		}
	}

	handleChange(type) {
		const cb = item => item.remindType == type
		const find = util.find(this.changed, cb)
		const exist = util.find(this.state.list, cb)
		const list = this.state.list.map(item => {
			if (item.remindType == type) {
				return {
					...item,
					status: 1-exist.status
				}
			}
			return item
		})
		// changed
		if (util.isNull(find)) {

			this.changed = [
				...this.changed,
				{
					remindSettingId: exist.remindSettingId,
					status: 1-exist.status
				}
			]
		} else {
			this.changed = this.changed.filter(item => item.remindType != type)
		}

		this.setState({
			list
		})
	}

	handleSubmit() {
		if (this.changed.length) {
			this.props.updateRemindSettings(this.changed, () => {
				success('更新成功!')
				this.changed = []
				this.props.fetchRemindSettings()
			})
		} else {
			warn('没有变动')
		}
	}

	renderList() {
		const { list } = this.state
		if (!list.length) return null
		return (
			<div className={style.list}>
				{
					list.map((item, i) => (
						<Checkbox 
							key={i}
							onClick={() => this.handleChange(item.remindType)}
							active={item.status} 
							label={item.remindName}/>
					))
				}
				<Button 
					onClick={::this.handleSubmit}
					className={style.button} 
					label="更新"/>
			</div>
		)
	}

	render() {
		return (
			<div className={style.root}>
				<TitleBar
					label="提醒设置"
				/>
        <h2>以下情况发送邮件提醒</h2>
				{ this.renderList() }
			</div>
		)
	}
}

